package cn.fl.risk.service.impl;

import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFFont;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.hssf.util.Region;
import org.apache.poi.ss.usermodel.CellStyle;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cmm.mid.core.framework.page.Pager;
import cn.cmm.base.framework.constant.BaseExceptionConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.DecimalUtils;
import cn.cmm.base.framework.utils.StringUtils;
import cn.fl.framework.base.context.CurrentThreadContext;
import cn.fl.project.ProjectUtils;
import cn.fl.project.condition.PrjPrdDtlQueryCondition;
import cn.fl.project.service.IPrjBscInfoService;
import cn.fl.project.service.IPrjPrdBscInfoService;
import cn.fl.project.service.IPrjPrdDtlService;
import cn.fl.project.service.IPrjPrdPaySchMService;
import cn.fl.project.vo.PrjBscInfoVO;
import cn.fl.project.vo.PrjPrdBscInfoVO;
import cn.fl.project.vo.PrjPrdDtlVO;
import cn.fl.project.vo.PrjPrdPaySchMVO;
import cn.fl.risk.api.IRskArreExpLogMApiService;
import cn.fl.risk.condition.RskArreExpLogMQC;
import cn.fl.risk.constant.RskArreExpLogMConstant;
import cn.fl.risk.dto.RskArreExpLogMDTO;
import cn.fl.risk.service.IRskArreExpLogMService;
import cn.fl.risk.transform.RskArreExpLogMVOTransform;
import cn.fl.risk.vo.RskArreExpLogDVO;
import cn.fl.risk.vo.RskArreExpLogMVO;

/**
 * @Description: 支付表欠款明细导出记录主表 客户端服务层接口实现
 * @Description: 业务层方法名称前缀：新增：add* 删除：remove* 修改：modify* 查询对象：select* get* 批量：batch* 查询集合：search*
 */
@Service
public class RskArreExpLogMServiceImpl implements IRskArreExpLogMService {

	/**
	 * 日志
	 */
	private static final Logger logger = LoggerFactory.getLogger(IRskArreExpLogMService.class);
	
	/**
	 * TODO 自定义 API 暴露服务
	 */
	@Autowired
	private IRskArreExpLogMApiService rskArreExpLogMApiService;
	
	@Autowired
	private IPrjPrdPaySchMService prjPrdPaySchMService;
	@Autowired
	private IPrjBscInfoService prjBscInfoService;
	
	@Autowired
	private IPrjPrdDtlService prjPrdDtlService;
	@Autowired
	private IPrjPrdBscInfoService prjPrdBscInfoService;
	

	@Override
	public RskArreExpLogMVO selectById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "selectById", "主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//TODO 业务逻辑
		RskArreExpLogMDTO dto = null;//this.自定义ApiService.selectById(id);
		return RskArreExpLogMVOTransform.toVO(dto);
	}

	@Override
	public Long add(RskArreExpLogMVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "add", "新增对象不能为空!", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//return this.rskArreExpLogMApiService.add(RskArreExpLogMVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return null;
	}

	@Override
	public boolean removeById(Long id) throws BaseException{
		if(StringUtils.isEmpty(id)){
			BaseLogUtils.info(logger, "removeById", "删除主键参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.rskArreExpLogMApiService.removeById(id);
		//TODO 业务逻辑
		return false;
	}
	
	/**
     * 删除
     * @param ids
     * @return
     */
    public boolean removeByIds(List<Long> ids)throws BaseException{
    	if(CollectionUtils.isEmpty(ids)){
    		BaseLogUtils.info(logger, "removeByIds", "删除主键参数集合不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		};
		return false;
    }

	@Override
	public boolean modify(RskArreExpLogMVO entity) throws BaseException{
		if(null == entity){
			BaseLogUtils.info(logger, "modify", "修改对象参数不能为空!", CurrentThreadContext.getCurrentUserName());
			return false;
		}
		//return this.rskArreExpLogMApiService.modify(RskArreExpLogMVOTransform.toDTO(entity));
		//TODO 业务逻辑
		return false;
	}

	@Override
	public Pager searchListPage(Pager page) throws BaseException{
		if(null == page)page = new Pager();
		
		page = this.rskArreExpLogMApiService.searchListPage(page,
				CurrentThreadContext.getCurrentSysCd(),
				CurrentThreadContext.getCurrentOrgCd());
		page.setResultList(RskArreExpLogMVOTransform.toVOList((List<RskArreExpLogMDTO>) page.getResultList()));
		return page;
	}

	@Override
	public List<RskArreExpLogMVO> exportArreExcelData(RskArreExpLogMQC mqc, FileOutputStream out) throws BaseException {
		RskArreExpLogMVO logMVO = null;
		List<RskArreExpLogMVO> logMList = new ArrayList<RskArreExpLogMVO>();
		if(CollectionUtils.isNotEmpty(mqc.getPayIdList())){
			 	HSSFWorkbook wb = new HSSFWorkbook();
	            HSSFFont headfont = wb.createFont();
	            headfont.setFontName("宋体");
	            headfont.setFontHeightInPoints((short) 22);// 字体大小
	            HSSFCellStyle headstyle = wb.createCellStyle();
	            headstyle.setFont(headfont);
	            headstyle.setAlignment(HSSFCellStyle.ALIGN_CENTER);// 左右居中
	            headstyle.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
	            headstyle.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
                headstyle.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
                headstyle.setBorderTop(CellStyle.BORDER_THIN);// 上边框
			    headstyle.setBorderRight(CellStyle.BORDER_THIN);// 右边框
	            
	            headstyle.setLocked(true);
		  try {
			for (Long payId : mqc.getPayIdList()) {
				PrjPrdPaySchMVO schm = 	this.prjPrdPaySchMService.selectPrjPrdPaySchMAndDetailById(payId);
				PrjBscInfoVO prjbscinfo = this.prjBscInfoService.selectById(schm.getPrjId());
				//产品明细、产品价格
				PrjPrdDtlQueryCondition dtlQc = new PrjPrdDtlQueryCondition();
				dtlQc.setPaySchId(payId);
				List<PrjPrdDtlVO>  dtlList = this.prjPrdDtlService.selectList(dtlQc);
				PrjPrdDtlVO dtlVO  = null;
				PrjPrdBscInfoVO prjPrdBscInfoVO = null;
				   String priceStr = "";
				   double price = 0;
				if(CollectionUtils.isNotEmpty(dtlList)){
					dtlVO = dtlList.get(0);
					prjPrdBscInfoVO = this.prjPrdBscInfoService.selectById(dtlVO.getPrjPrdId());
					   price = prjPrdBscInfoVO.getGuidePc() == null ? 0 : DecimalUtils.convertFenToYuan(prjPrdBscInfoVO.getGuidePc().longValue());
					   BigDecimal bd = new BigDecimal(price);
                       priceStr = bd.toPlainString();
				}
				
				   HSSFSheet sheet = wb.createSheet(schm.getPaySchNo()+"欠款明细");
				   sheet.setDefaultColumnWidth(15);
				   sheet.setDefaultRowHeightInPoints(15);

		            HSSFCellStyle style = wb.createCellStyle();
		            style.setAlignment(HSSFCellStyle.ALIGN_CENTER); // 创建一个居中格式
		            style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		            // 普通单元格样式（中文）
		            HSSFFont font2 = wb.createFont();
		            font2.setFontName("宋体");
		            font2.setFontHeightInPoints((short) 12);
		            style.setFont(font2);
		            style.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
		            style.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
		            style.setBorderTop(CellStyle.BORDER_THIN);// 上边框
		            style.setBorderRight(CellStyle.BORDER_THIN);// 右边框
		            
		            
		            HSSFCellStyle style1 = wb.createCellStyle();
		            style1.setAlignment(HSSFCellStyle.ALIGN_LEFT); // 创建一个居中格式
		            style1.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		            // 普通单元格样式（中文）
		            HSSFFont font3 = wb.createFont();
		            font3.setFontName("宋体");
		            font3.setFontHeightInPoints((short) 12);
		            style1.setFont(font3);
		            style1.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
		            style1.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
		            style1.setBorderTop(CellStyle.BORDER_THIN);// 上边框
		            style1.setBorderRight(CellStyle.BORDER_THIN);// 右边框
		            
		            
		            HSSFCellStyle style2 = wb.createCellStyle();
		            style2.setAlignment(HSSFCellStyle.ALIGN_RIGHT); // 创建一个居中格式
		            style2.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);// 上下居中
		            // 普通单元格样式（中文）
		            HSSFFont font4 = wb.createFont();
		            font4.setFontName("宋体");
		            font4.setFontHeightInPoints((short) 12);
		            style2.setFont(font4);
		            style2.setBorderBottom(CellStyle.BORDER_THIN); // 下边框
		            style2.setBorderLeft(CellStyle.BORDER_THIN);// 左边框
		            style2.setBorderTop(CellStyle.BORDER_THIN);// 上边框
		            style2.setBorderRight(CellStyle.BORDER_THIN);// 右边框
		            

		            HSSFRow titleRow = sheet.createRow((int) 0);
		            HSSFCell titleCell = titleRow.createCell(0);
		            titleCell.setCellValue(prjbscinfo.getCstNm()+" 欠款明细");
		            titleCell.setCellStyle(headstyle);
		            Region region = new Region(0, (short) 0, 0, (short) 14);
	                sheet.addMergedRegion(region);
		            
		            /*HSSFRow lineRow = sheet.createRow((int) 1);
		            HSSFCell lineCell = lineRow.createCell(0);
		            lineCell.setCellValue("=");
		            lineCell.setCellStyle(headstyle);
		            Region lineRegion = new Region(1, (short) 0, 1, (short) 15);
	                sheet.addMergedRegion(lineRegion);*/

		            HSSFRow noRow = sheet.createRow((int) 1);
		            HSSFCell noCell = noRow.createCell(0);
		            noCell.setCellValue(" ");
		            noCell.setCellStyle(style);
		            noCell = noRow.createCell(1);
		            noCell.setCellValue("函编号：");
		            noCell.setCellStyle(style);
		            noCell = noRow.createCell(2);
		            noCell.setCellValue(" ");
		            noCell.setCellStyle(style);
		            Region noRegion = new Region(1, (short) 0, 1, (short) 13);
	                sheet.addMergedRegion(noRegion);
		            
	                
	                HSSFRow descRow = sheet.createRow((int) 2);
		            HSSFCell descCell = descRow.createCell(0);
		            descCell.setCellValue("截至"+DateUtils.formatDateToString(mqc.getClosDt(), DateUtils.YYYY_MM_DD_ZH)+"承租人"+prjbscinfo.getCstNm()+" 与我司账务来款明细情况如下：");
		            descCell.setCellStyle(style1);
		            Region  descRegion = new Region(2, (short) 0, 2, (short) 14);
	                sheet.addMergedRegion(descRegion);
		            
		            
		            //产品信息
		            HSSFRow prdRow = sheet.createRow((int) 3);
		            HSSFCell prdcell = prdRow.createCell(0);
		            prdcell.setCellValue("支付表编号");
		            prdcell.setCellStyle(style);

		            prdcell = prdRow.createCell(1);
		            prdcell.setCellValue("设备名称");
		            prdcell.setCellStyle(style);
		            prdcell = prdRow.createCell(2);
		            prdcell.setCellValue("设备数量");
		            prdcell.setCellStyle(style);

		            prdcell = prdRow.createCell(3);
		            prdcell.setCellValue("设备金额");
		            prdcell.setCellStyle(style);

		            prdcell = prdRow.createCell(4);
		            prdcell.setCellValue("租金总额");
		            prdcell.setCellStyle(style);
		            //产品信息s
		            HSSFRow prdValueRow = sheet.createRow((int) 4);
		            HSSFCell prdValueCell = prdValueRow.createCell(0);
		            prdValueCell.setCellValue(schm.getPaySchNo());
		            prdValueCell.setCellStyle(style);

		            prdValueCell = prdValueRow.createCell(1);
		            prdValueCell.setCellValue(dtlVO.getPrdNm());
		            prdValueCell.setCellStyle(style);

		            prdValueCell = prdValueRow.createCell(2);
		            prdValueCell.setCellValue(dtlVO.getPrdQty());
		            prdValueCell.setCellStyle(style);

		            prdValueCell = prdValueRow.createCell(3);
		            prdValueCell.setCellValue(priceStr);
		            prdValueCell.setCellStyle(style);

		            prdValueCell = prdValueRow.createCell(4);
		            prdValueCell.setCellValue(schm.getTotalRntAmt());
		            prdValueCell.setCellStyle(style);
		            
		            HSSFRow blankRow = sheet.createRow((int) 5);
		            HSSFCell blankCell = blankRow.createCell(0);
		            blankCell.setCellValue(" ");
		            
		            HSSFRow blankRow1 = sheet.createRow((int) 6);
		            HSSFCell blankCell1 = blankRow1.createCell(0);
		            blankCell1.setCellValue(" ");
		            
		            mqc.setPayId(payId);
		            mqc.setCstId(prjbscinfo.getCstId());
		            mqc.setCstNm(prjbscinfo.getCstNm());
			    	 logMVO =RskArreExpLogMVOTransform.toVO(rskArreExpLogMApiService.searchLogMExportDataByCond(mqc,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));
			    	 logMVO.setCrtTm(new Date());
			    	 logMVO.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
			    	 logMVO.setPaySchNo(schm.getPaySchNo());
			    	 logMVO.setLsCntNo(prjbscinfo.getLsCntNo());
			    	 logMVO.setCstId(prjbscinfo.getCstId());
			    	 logMVO.setCstNm(prjbscinfo.getCstNm());
		            //支付表费用信息列表
		            List<RskArreExpLogDVO> amtList = logMVO.getLogDList();
		            
		          //产品信息
		            HSSFRow payRow = sheet.createRow((int) 7);
		            HSSFCell paycell = payRow.createCell(0);
		            paycell.setCellValue("融资租赁支付表号");
		            paycell.setCellStyle(style);

		            paycell = payRow.createCell(1);
		            paycell.setCellValue("期次");
		            paycell.setCellStyle(style);
		            paycell = payRow.createCell(2);
		            paycell.setCellValue("应付日期");
		            paycell.setCellStyle(style);

		            paycell = payRow.createCell(3);
		            paycell.setCellValue("应付金额");
		            paycell.setCellStyle(style);

		            paycell = payRow.createCell(4);
		            paycell.setCellValue("实付日期");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(5);
		            paycell.setCellValue("实付金额");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(6);
		            paycell.setCellValue("逾期金额");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(7);
		            paycell.setCellValue("逾期天数");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(8);
		            paycell.setCellValue("应收罚息");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(9);
		            paycell.setCellValue("实收罚息");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(10);
		            paycell.setCellValue("应收违约金");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(11);
		            paycell.setCellValue("实收违约金");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(12);
		            paycell.setCellValue("来款日期");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(13);
		            paycell.setCellValue("纪要");
		            paycell.setCellStyle(style);
		            
		            paycell = payRow.createCell(14);
		            paycell.setCellValue("来款金额");
		            paycell.setCellStyle(style);
		            double feeAmtTotal = 0d;// 应收金额合计
		            double arAmtTotal = 0d;//实收金额合计
		            double overAmtTotal = 0d;//逾期金额合计
		            double penaltyAmtTotal = 0d;//罚息金额合计
		            double arPenaltyAmtTotal = 0d;//实收罚息合计
		            double payAmtTotal = 0d;//来款金额合计
		            double breachAmtTotal = 0d;//罚息金额合计
		             
		            for (int i=0;i<amtList.size();i++) {
		            	RskArreExpLogDVO logDVO = amtList.get(i);
		            	 HSSFRow row = sheet.createRow((int) i +8);
		                 HSSFCell payCell = row.createCell(0);
		                 payCell.setCellValue(schm.getPaySchNo());
		                 payCell.setCellStyle(style);
		                 String pd =  logDVO.getLsPd()==0?"首期款":logDVO.getLsPd().toString();
		                 payCell = row.createCell(1);
		                 payCell.setCellValue(pd);
		                 payCell.setCellStyle(style);

		                 payCell = row.createCell(2);
		                 payCell.setCellValue(DateUtils.formatDateToString(logDVO.getPayDt(), DateUtils.YYYY_MM_DD));
		                 payCell.setCellStyle(style);

		                 payCell = row.createCell(3);
		                 payCell.setCellValue(null==logDVO.getFeeAmt()?"":logDVO.getFeeAmt().toString());
		                 payCell.setCellStyle(style);
		                 feeAmtTotal = DecimalUtils.add(feeAmtTotal, null==logDVO.getFeeAmt()?0:logDVO.getFeeAmt());
		                 
		                 payCell = row.createCell(4);
		                 payCell.setCellValue(DateUtils.formatDateToString(logDVO.getArPayDt(), DateUtils.YYYY_MM_DD));
		                 payCell.setCellStyle(style);

		                 payCell = row.createCell(5);
		                 payCell.setCellValue(null==logDVO.getArAmt()?"":logDVO.getArAmt().toString());
		                 payCell.setCellStyle(style);
		                 arAmtTotal = DecimalUtils.add(arAmtTotal,null==logDVO.getArAmt()?0:logDVO.getArAmt());
		                 
		                 payCell = row.createCell(6);
		                 payCell.setCellValue(null==logDVO.getOverdueAmt()?"":logDVO.getOverdueAmt().toString());
		                 payCell.setCellStyle(style);
		                 overAmtTotal = DecimalUtils.add(overAmtTotal, null==logDVO.getOverdueAmt()?0:logDVO.getOverdueAmt());
		                 
		                 payCell = row.createCell(7);
		                 payCell.setCellValue(null==logDVO.getOverdueDay()?"":logDVO.getOverdueDay().toString());
		                 payCell.setCellStyle(style);
		            	
		                 payCell = row.createCell(8);
		                 payCell.setCellValue(null==logDVO.getPenaltyAmt()?"":logDVO.getPenaltyAmt().toString());
		                 payCell.setCellStyle(style);
		                 penaltyAmtTotal = DecimalUtils.add(penaltyAmtTotal, null==logDVO.getPenaltyAmt()?0:logDVO.getPenaltyAmt());
		                 
		                 payCell = row.createCell(9);
		                 payCell.setCellValue(null==logDVO.getArPenalarAmt()?"":logDVO.getArPenalarAmt().toString());
		                 payCell.setCellStyle(style);
		                 arPenaltyAmtTotal = DecimalUtils.add(arPenaltyAmtTotal, null==logDVO.getArPenalarAmt()?0:logDVO.getArPenalarAmt());
		                 
		                 payCell = row.createCell(10);
		                 payCell.setCellValue(null==logDVO.getBreachAmt()?"":logDVO.getBreachAmt().toString());
		                 payCell.setCellStyle(style);
		                 breachAmtTotal = DecimalUtils.add(breachAmtTotal, null==logDVO.getBreachAmt()?0:logDVO.getBreachAmt());
		                 
		                 payCell = row.createCell(11);
		                 payCell.setCellValue(null==logDVO.getArBreachAmt()?"":logDVO.getArBreachAmt().toString());
		                 payCell.setCellStyle(style);
		                 
		                 payCell = row.createCell(12);
		                 payCell.setCellValue(DateUtils.formatDateToString(logDVO.getPaymentDt(), DateUtils.YYYY_MM_DD));
		                 payCell.setCellStyle(style);
		                 
		                 payCell = row.createCell(13);
		                 payCell.setCellValue(null==logDVO.getPaymentWayCdNm()?"":logDVO.getPaymentWayCdNm());
		                 payCell.setCellStyle(style);
		                 
		                 payCell = row.createCell(14);
		                 payCell.setCellValue(null==logDVO.getPaymentAmt()?"":logDVO.getPaymentAmt().toString());
		                 payCell.setCellStyle(style);
		                 payAmtTotal = DecimalUtils.add(payAmtTotal,null==logDVO.getPaymentAmt()?0:logDVO.getPaymentAmt());
					}
		            
		            HSSFRow totalRow = sheet.createRow((int) amtList.size()+8);
		            HSSFCell totalCell = totalRow.createCell(0);
		            totalCell.setCellValue("金额合计");
		            totalCell.setCellStyle(style);

		            Region  totalRegion = new Region(amtList.size()+8, (short) 0, amtList.size()+8, (short) 2);
	                sheet.addMergedRegion(totalRegion);
		            if(feeAmtTotal<0){
		            	feeAmtTotal = 0;
		            }
	                
		            totalCell = totalRow.createCell(3);
		            totalCell.setCellValue(0==feeAmtTotal?"":String.valueOf(feeAmtTotal));
		            totalCell.setCellStyle(style);
		            
		            totalCell = totalRow.createCell(4);
		            totalCell.setCellValue(" ");
		            totalCell.setCellStyle(style);
		            
		            if(arAmtTotal<0){
		            	arAmtTotal = 0;
		            }
		            totalCell = totalRow.createCell(5);
		            totalCell.setCellValue(0==arAmtTotal?"":String.valueOf(arAmtTotal));
		            totalCell.setCellStyle(style);

		            if(overAmtTotal<0){
		            	overAmtTotal = 0;
		            }
		            totalCell = totalRow.createCell(6);
		            totalCell.setCellValue(0==overAmtTotal?"":String.valueOf(overAmtTotal));
		            totalCell.setCellStyle(style);
		            
		            totalCell = totalRow.createCell(7);
		            totalCell.setCellValue(" ");
		            totalCell.setCellStyle(style);
		            
		            if(penaltyAmtTotal<0){
		            	penaltyAmtTotal = 0;
		            }
		            totalCell = totalRow.createCell(8);
		            totalCell.setCellValue(0==penaltyAmtTotal?"":String.valueOf(penaltyAmtTotal));
		            totalCell.setCellStyle(style);
		            
		            if(arPenaltyAmtTotal<0){
		            	arPenaltyAmtTotal = 0;
		            }
		            totalCell = totalRow.createCell(9);
		            totalCell.setCellValue(0==arPenaltyAmtTotal?"":String.valueOf(arPenaltyAmtTotal));
		            totalCell.setCellStyle(style);
		            
		            totalCell = totalRow.createCell(10);
		            totalCell.setCellValue(" ");
		            totalCell.setCellStyle(style);
		            
		            totalCell = totalRow.createCell(11);
		            totalCell.setCellValue(" ");
		            totalCell.setCellStyle(style);
		            
		            totalCell = totalRow.createCell(12);
		            totalCell.setCellValue("来款合计");
		            totalCell.setCellStyle(style);
		            
		            Region  totalRegion1 = new Region(amtList.size()+8, (short) 12, amtList.size()+8, (short) 13);
	                sheet.addMergedRegion(totalRegion1);
		            
	                if(payAmtTotal<0){
	                	payAmtTotal = 0;
		            }
		            totalCell = totalRow.createCell(14);
		            totalCell.setCellValue(payAmtTotal);
		            totalCell.setCellStyle(style);
		            
		            HSSFRow total2Row = sheet.createRow((int) amtList.size()+9);
		            HSSFCell total2Cell = total2Row.createCell(0);
		            total2Cell.setCellValue("截至"+DateUtils.formatDateToString(mqc.getClosDt(), DateUtils.YYYY_MM_DD)+"欠款合计");
		            total2Cell.setCellStyle(style);
		            Region  totalRegion2 = new Region(amtList.size()+9, (short) 0, amtList.size()+9, (short) 2);
		            sheet.addMergedRegion(totalRegion2);
		            
		            double arreTotalAmt = feeAmtTotal-arAmtTotal+penaltyAmtTotal-arPenaltyAmtTotal+breachAmtTotal;
		             total2Cell = total2Row.createCell(3);
		          /*   BigDecimal bd1 = new BigDecimal(arreTotalAmt);
                     String arreTotalAmtStr = bd1.toPlainString();*/
		             if(arreTotalAmt<0){
		            	 arreTotalAmt = 0;
			            }
		             String  val  = BigDecimal.valueOf(arreTotalAmt).setScale(2, RoundingMode.HALF_UP).toPlainString();
		            total2Cell.setCellValue(0==arreTotalAmt?"":val);
		            total2Cell.setCellStyle(style);
		            
		            total2Cell = total2Row.createCell(4);
		            total2Cell.setCellValue("大写：人民币");
		            total2Cell.setCellStyle(style);

		            double balanceTestAmt = feeAmtTotal-arAmtTotal-overAmtTotal+arPenaltyAmtTotal+arAmtTotal-payAmtTotal;
		            if(balanceTestAmt<0){
		            	balanceTestAmt = 0;
			            }
		            total2Cell = total2Row.createCell(5);
		            total2Cell.setCellValue(ProjectUtils.hangeToBig(arreTotalAmt));
		            total2Cell.setCellStyle(style1);
		            Region  totalRegion3 = new Region(amtList.size()+9, (short) 5, amtList.size()+9, (short) 11);
		            sheet.addMergedRegion(totalRegion3);
		            
		            total2Cell = total2Row.createCell(12);
		            total2Cell.setCellValue("来款平衡试算");
		            total2Cell.setCellStyle(style);
		            
		            Region  totalRegion4 = new Region(amtList.size()+9, (short) 12, amtList.size()+9, (short) 13);
	                sheet.addMergedRegion(totalRegion4);
		            
		            total2Cell = total2Row.createCell(14);
		            total2Cell.setCellValue(0==balanceTestAmt?"0":String.valueOf(balanceTestAmt));
		            total2Cell.setCellStyle(style);
		            
		            String str = "";
		            if(mqc.getPenaCalWay().equals(RskArreExpLogMConstant.CODE_PENA_CAL_WAY_CD_1)){
		            	str+="违约金是租金总额的百分之八，年利率百分之24单利计算到"+DateUtils.formatDateToString(mqc.getClosDt(), DateUtils.YYYY_MM_DD);
		            }
		            
		            if(mqc.getPenaCalWay().equals(RskArreExpLogMConstant.CODE_PENA_CAL_WAY_CD_2)){
		            	str+="违约金为履约保证金的千分之十五，自最长应付款日起至明细表核算截止日逐日计算";
		            }
		            HSSFRow total3Row = sheet.createRow((int) amtList.size()+10);
		            HSSFCell total3Cell = total3Row.createCell(0);
		            total3Cell.setCellValue(str);
		            total3Cell.setCellStyle(style1);
		            
		            Region  totalRegion5 = new Region(amtList.size()+10, (short) 0, amtList.size()+10, (short) 14);
	                sheet.addMergedRegion(totalRegion5);
		            
		            HSSFRow total4Row = sheet.createRow((int) amtList.size()+11);
		            HSSFCell total4Cell = total4Row.createCell(0);
		            total4Cell.setCellValue("制表："+CurrentThreadContext.getCurrentUserName());
		            total4Cell.setCellStyle(style1);
		            
		            Region  totalRegion6 = new Region(amtList.size()+11, (short) 0, amtList.size()+11, (short) 14);
	                sheet.addMergedRegion(totalRegion6);
		            
		            HSSFRow total5Row = sheet.createRow((int) amtList.size()+12);
		            HSSFCell total5Cell = total5Row.createCell(0);
		            total5Cell.setCellValue(" 狮桥融资租赁（中国）有限公司");
		            total5Cell.setCellStyle(style2);
		            Region  totalRegion7 = new Region(amtList.size()+12, (short) 0, amtList.size()+12, (short) 14);
	                sheet.addMergedRegion(totalRegion7);
		            
		            /*total5Cell = total5Row.createCell(1);
		            total5Cell.setCellValue("狮桥融资租赁（中国）有限公司");
		            total5Cell.setCellStyle(style);
		            Region  totalRegion8 = new Region(amtList.size()+12, (short) 12, amtList.size()+12, (short) 15);
	                sheet.addMergedRegion(totalRegion8);*/
		            
		            HSSFRow total6Row = sheet.createRow((int) amtList.size()+13);
		            HSSFCell total6Cell = total6Row.createCell(0);
		            total6Cell.setCellValue(DateUtils.formatDateToString(mqc.getClosDt(), DateUtils.YYYY_MM_DD));
		            total6Cell.setCellStyle(style2);
		            Region  totalRegion9 = new Region(amtList.size()+13, (short) 0, amtList.size()+13, (short) 14);
	                sheet.addMergedRegion(totalRegion9);
	                
		            /*total6Cell = total6Row.createCell(1);
		            total6Cell.setCellValue(DateUtils.formatDateToString(mqc.getClosDt(), DateUtils.YYYY_MM_DD));
		            total6Cell.setCellStyle(style);
		            Region  totalRegion10 = new Region(amtList.size()+13, (short) 12, amtList.size()+13, (short) 15);
	                sheet.addMergedRegion(totalRegion10);*/
		            
		            logMList.add(logMVO);
			}
			  wb.write(out);
			  out.flush();
			   out.close() ;
		   } catch (Exception e) {
				BaseLogUtils.info(logger, "exportPrjPrdPaySch", "导出支付表失败"+e.getMessage(), CurrentThreadContext.getCurrentUserName());
               throw new BaseException(BaseExceptionConstant.BASE_EXCEPTION_CODE_405_NAME, "导出失败，文件处理错误！");
           } finally {
           }
		}
		return logMList;
	}

	@Override
	public boolean addArreExpLogByCond(List<RskArreExpLogMVO> logMVO) throws BaseException {
		
		return this.rskArreExpLogMApiService.addArreExpLogByCond(RskArreExpLogMVOTransform.toDTOList(logMVO));
	}

	@Override
	public RskArreExpLogMVO selectRskArreExpLogMAndDetailById(Long logMId) throws BaseException {
		RskArreExpLogMVO vo = RskArreExpLogMVOTransform.toVO(this.rskArreExpLogMApiService.selectRskArreExpLogMAndDetailById(logMId,CurrentThreadContext.getCurrentSysCd(),CurrentThreadContext.getCurrentOrgCd()));
		vo = getTotalValue(vo);
		return vo;
	}

	private RskArreExpLogMVO getTotalValue(RskArreExpLogMVO logMVO) {
		 double feeAmtTotal = 0d;// 应收金额合计
         double arAmtTotal = 0d;//实收金额合计
         double overAmtTotal = 0d;//逾期金额合计
         double penaltyAmtTotal = 0d;//罚息金额合计
         double arPenaltyAmtTotal = 0d;//实收罚息合计
         double payAmtTotal = 0d;//来款金额合计
         double breachAmtTotal = 0d;//罚息金额合计
         List <RskArreExpLogDVO> amtList = logMVO.getLogDList();
         for (int i=0;i<amtList.size();i++) {
         	RskArreExpLogDVO logDVO = amtList.get(i);
         	double feeAmt = DecimalUtils.convertFenToYuan(logDVO.getFeeAmt().longValue());
			//分转元
         	logDVO.setArAmt(DecimalUtils.convertFenToYuan(null==logDVO.getArAmt()?0l:logDVO.getArAmt().longValue()));
         	logDVO.setArBreachAmt(DecimalUtils.convertFenToYuan(null==logDVO.getArBreachAmt()?0l:logDVO.getArBreachAmt().longValue()));
         	logDVO.setArPenalarAmt(DecimalUtils.convertFenToYuan(null==logDVO.getArPenalarAmt()?0l:logDVO.getArPenalarAmt().longValue()));
			logDVO.setFeeAmt(DecimalUtils.convertFenToYuan(null==logDVO.getFeeAmt()?0l:logDVO.getFeeAmt().longValue()));
			logDVO.setOverdueAmt(DecimalUtils.convertFenToYuan(null==logDVO.getOverdueAmt()?0l:logDVO.getOverdueAmt().longValue()));
			logDVO.setPenaltyAmt(DecimalUtils.convertFenToYuan(null==logDVO.getPenaltyAmt()?0l:logDVO.getPenaltyAmt().longValue()));
			logDVO.setArPenalarAmt(DecimalUtils.convertFenToYuan(null==logDVO.getPenaltyAmt()?0l:logDVO.getArPenalarAmt().longValue()));
			logDVO.setBreachAmt(DecimalUtils.convertFenToYuan(null==logDVO.getBreachAmt()?0l:logDVO.getBreachAmt().longValue()));
			logDVO.setArBreachAmt(DecimalUtils.convertFenToYuan(null==logDVO.getArBreachAmt()?0l:logDVO.getArBreachAmt().longValue()));
			logDVO.setPaymentAmt(DecimalUtils.convertFenToYuan(null==logDVO.getPaymentAmt()?0l:logDVO.getPaymentAmt().longValue()));
			
         	
         	
         	feeAmtTotal = DecimalUtils.add(feeAmtTotal, feeAmt);
         	arAmtTotal = DecimalUtils.add(arAmtTotal, feeAmt);
             overAmtTotal = DecimalUtils.add(overAmtTotal, feeAmt);
             penaltyAmtTotal = DecimalUtils.add(penaltyAmtTotal, feeAmt);
			 arPenaltyAmtTotal = DecimalUtils.add(arPenaltyAmtTotal, feeAmt);
			 breachAmtTotal = DecimalUtils.add(breachAmtTotal, feeAmt);
			 payAmtTotal = DecimalUtils.add(payAmtTotal, feeAmt);
         	}
         logMVO.setFeeAmtTotal(feeAmtTotal);
         logMVO.setArAmtTotal(arAmtTotal);
         logMVO.setOverAmtTotal(overAmtTotal);
         logMVO.setPenaltyAmtTotal(arPenaltyAmtTotal);
         logMVO.setArPenaltyAmtTotal(arPenaltyAmtTotal);
         logMVO.setBreachAmtTotal(breachAmtTotal);
         logMVO.setPayAmtTotal(payAmtTotal);
		return logMVO;
	}
}
